package com.naiterui.ehp.bs.patient.service.impl;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.constants.CommonConstant;
import com.naiterui.ehp.bp.constants.PaQrCodeEnum;
import com.naiterui.ehp.bp.utils.beans.BeanUtil;
import com.naiterui.ehp.bp.utils.beans.XmlMapper;
import com.naiterui.ehp.bs.patient.bo.notice.RegisterParamBO;
import com.naiterui.ehp.bs.patient.config.SubscribeConfig;
import com.naiterui.ehp.bs.patient.service.IPatientService;
import com.naiterui.ehp.bs.patient.service.IWeChatMessageService;
import com.naiterui.ehp.bs.wechat.constants.WeChatConstant;
import com.naiterui.ehp.bs.wechat.param.EventSubscribe;
import com.naiterui.ehp.bs.wechat.protocol.result.UserInfo;
import com.naiterui.ehp.bs.wechat.service.IWeChatUserService;
import java.time.LocalDateTime;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhoupeipei
 * @date 2019-06-28 14:39
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class ApWeChatMessageServiceImpl implements IWeChatMessageService {
    private static Logger LOGGER = LoggerFactory.getLogger(ApWeChatMessageServiceImpl.class);

    @Autowired
    IWeChatUserService weChatUserService;
    @Autowired
    IPatientService patientService;
    private final SubscribeConfig subscribeConfig;

    @Override
    public String handleEventMessage(String openId, String xmlBody) {
        LOGGER.info("关注、取关、扫码、订阅通知事件：{},用户：{}", xmlBody, openId);
        if (StringUtils.isBlank(openId) || StringUtils.isBlank(xmlBody)) {
            LOGGER.error("参数错误");
            return "";
        }

        // 事件消息
        EventSubscribe eventSubscribe = XmlMapper.fromXml(xmlBody, EventSubscribe.class);

        String event = Optional.ofNullable(eventSubscribe).map(EventSubscribe::getEvent).orElse("");
        String scene = eventSubscribe.getEventKey();
        switch (event) {
            case WeChatConstant.EventType.SUBSCRIBE:
                //更新用户活跃失效
                RedisUtil.valueOps().setString(CommonConstant.CONSULT_PATIENT_ACTIVE + openId, openId, 48 * 60 * 60);
                //关注公众号，搜索关注、扫码关注
                UserInfo user = weChatUserService.userInfo(openId);

                boolean haveScene = StringUtils.isNotBlank(scene);
                // 注册来源
                int source = 0;
                if (haveScene) {
                    source = RegisterParamBO.AD_INVITE_SOURCE;
                } else {
                    source = RegisterParamBO.ME_REG_SOURCE;
                }

                RegisterParamBO registerParamBO = new RegisterParamBO(source);
                BeanUtil.copyProperties(user, registerParamBO);

                try {
                    patientService.saveRegisterInfo(registerParamBO);
                } catch (Exception e) {
                    LOGGER.error("用户注册异常", e);
                }

                //扫码关注处理扫码逻辑
                if (haveScene) {
                    this.scan(openId, scene);
                }
                break;
            case WeChatConstant.EventType.UNSUBSCRIBE:
                //取消关注
                try {
                    patientService.cancelAttend(openId);
                } catch (Exception e) {
                    LOGGER.error("用户取消关注异常", e);
                }
                break;

            case WeChatConstant.EventType.SCAN:
                //更新用户活跃失效
                RedisUtil.valueOps().setString(CommonConstant.CONSULT_PATIENT_ACTIVE + openId, openId, 48 * 60 * 60);
                //扫码，已关注公众号
                if (StringUtils.isNotBlank(scene)) {
                    this.scan(openId, scene);
                }
                break;
            case WeChatConstant.EventType.SUBSCRIBE_MSG_POPUP_EVENT:
                // 订阅通知事件
                break;
            default:
                break;

        }

        return "";
    }

    /**
     * 二维码扫描
     *
     * @param openId
     * @param scene
     */
    private void scan(String openId, String scene) {
        if (StringUtils.isBlank(openId) || StringUtils.isBlank(scene)) {
            LOGGER.error("异常扫码请求，openId:{},scene:{}", openId, scene);
            return;
        }
        boolean subCustom = scene.startsWith("qrscene_");
        if (subCustom) {
            scene = scene.replace("qrscene_", "");
        }
        // 扫描医生邀请码
        if (scene.contains(PaQrCodeEnum.INVITE.getValue())) {
            String doctorId = scene.replace(PaQrCodeEnum.INVITE.getValue(), "");
            try {
                patientService.saveBindInfo(openId, Long.valueOf(doctorId));
            } catch (Exception e) {
                LOGGER.error("扫描邀请码异常", e);
            }
        } else if (scene.contains(PaQrCodeEnum.SIGN_IN.getValue())) {
            if (LocalDateTime.now().isBefore(LocalDateTime.of(2021, 07, 11, 23, 59, 59))) {
                // 签到逻辑(扫特定二维码)
                patientService.sendSignInMsg(openId);
            }
        }

    }

}
